package com.nulldev.util.scripting.ScriptAPI.baseJS.legacy.lexer;

import java.util.Map;

import com.nulldev.util.VariableAPI.util.strings.splitters.Splitters;
import com.nulldev.util.data.Arrays.maps.FastMaps;
import com.nulldev.util.scripting.ScriptAPI.baseJS.legacy.lexer.global.BaseJSNativeFunction;

public class BaseJSObject {
	public final String name;

	public final Map<String, BaseJSObject> contents;

	public BaseJSObject(final String name) {
		this.name = name.trim();
		this.contents = FastMaps.map();
	}

	public BaseJSObject(final String name, final Map<String, BaseJSObject> contents) {
		this.name = name.trim();
		this.contents = contents;
	}

	@Override
	public String toString() {
		return "BaseJSObject[name: " + name + ", contents: " + contents + "]";
	}

	public BaseJSObject get(final String string) {
		if (string == null || string.isEmpty() || !contents.containsKey(string)) {
			throw new MissingObjectError(string + " wasn't found in the environment.");
		} else
			return contents.get(string);
	}

	public BaseJSObject mGet(final String invokeTarget) {
		BaseJSObject out = null;
		final String[] f = Splitters.splitString(invokeTarget, ".");
		for (final String n : f) {
			if (out == null)
				out = this.get(n);
			else {
				out = out.get(n);
				if (out == null)
					break;
			}
		}
		return out;
	}

	public boolean isFunction() {
		return this instanceof BaseJSFunction || this instanceof BaseJSNativeFunction;
	}

	public boolean contains(final String func) {
		if (func == null || func.isEmpty())
			return false;
		return contents.containsKey(func);
	}

	public boolean isVariable() {
		return this instanceof BaseJSVariable;
	}

	public boolean isNativeFunction() {
		return this instanceof BaseJSNativeFunction;
	}
}
